package site.kuangzhang.probe.handler;

import site.kuangzhang.probe.pojo.Miner;
import site.kuangzhang.probe.util.Http;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;

public class HandlerFacotry {

	private static final String ANTMINER = "antminer";

	public static final String UNKNOW = "未知";

	public static Handler create(Miner miner) {

		if (!isHostConnectable(miner)) {
			return new UnknowHandler(miner);
		}

		String type = UNKNOW;

		try {
			//判断是否是蚂蚁矿机
			String content = Http.getByProvider("http://" + miner.getIp() + "/cgi-bin/get_system_info.cgi", "root","root");
			if (content.contains("Antminer")) {
				type = ANTMINER;
			}
		} catch (Exception e) {
		}

		switch (type) {
			case ANTMINER:
				return new AntminerHandler(miner);
			default:
				return new UnknowHandler(miner);
		}

	}

	public static boolean isHostConnectable(Miner miner) {
		Socket socket = new Socket();
		try {
			socket.connect(new InetSocketAddress(miner.getIp(), 80), 3000);
		} catch (Exception e) {
			return false;
		} finally {
			try {
				socket.close();
			} catch (IOException e) {
			}
		}
		return true;
	}

}
